//
// 作者：AKA_GGbond
// 时间：2025/7/17
// 邮箱：evain_wl@163.com
//

#include "W_Sql.h"
#include <QApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QFile>
#include <QGlobalStatic>

Q_GLOBAL_STATIC(W_Sql,s_instance)

W_Sql::W_Sql(QObject *parent)
    : QObject(parent)
{
    initSql();
}

W_Sql::~W_Sql()
{

}

bool W_Sql::Search(const QString &sql)
{
    QSqlQuery query(QSqlDatabase::database(m_conn_name));
    if(!query.exec(sql))
    {
        return false;
    }
    else
    {
        // 检查查询结果
        if (query.next())
        {
            int userExists = query.value(0).toInt();
            return (userExists == 1) ? true : false;
        }
        else
        {
            return false;
        }
    }
}

void W_Sql::initSql()
{
    m_conn_name = "userConnection";
    //默认取应用程序可执行文件目录
    QString path = qApp->applicationDirPath();
    QSqlDatabase dbConn = QSqlDatabase::addDatabase("QSQLITE",m_conn_name);
    QString tmp_dbpath = path + "/user.db";
    dbConn.setDatabaseName(tmp_dbpath);
    //判断数据库文件是否存在，必须先判断文件在不，因为open就会创建db，后面在判断就没作用
    QFile filedb(tmp_dbpath);
    if(filedb.exists())
    {
        if (dbConn.open()) {
        } else {
            return;
        }
    }
    else
    {
        if (dbConn.open()) {
        } else {
            return;
        }

        createDb();
    }
}

void W_Sql::createDb()
{
    QString create_tabel_sql = "CREATE TABLE IF NOT EXISTS UserInfoModel(\
            id INTEGER PRIMARY KEY AUTOINCREMENT,\
            userName TEXT,\
            userPasswd TEXT)";

    if(executSQL(create_tabel_sql))
    {
        //插入
        QString insert_sql = QString("insert into UserInfoModel(userName,userPasswd) values ('%1','%2');")
                .arg("超级用户").arg("root");
        executSQL(insert_sql);

        insert_sql = QString("insert into UserInfoModel(userName,userPasswd) values ('%1','%2');")
                .arg("普通用户").arg("123456");
        executSQL(insert_sql);
    }
}

bool W_Sql::executSQL(const QString &sql)
{
    QSqlQuery query(QSqlDatabase::database(m_conn_name));
    if(!query.exec(sql))
    {
        return false;
    }

    return true;
}

W_Sql *W_Sql::Instance() {
    return s_instance;
}
